import React, { useState, useEffect } from 'react';
import { upload } from '@/utils/upload';
import Taro from '@tarojs/taro';
import { View, Image } from '@tarojs/components'
import './index.scss';

export default ({
  count = 9,
  data = [],
  onChange,
  className,
  classChangeName,
  toast = '添加图片',
}) => {
  const [list, setList] = useState([]);

  useEffect(() => {
    if (data && data.length) {
      setList([...JSON.parse(JSON.stringify(data))]);
    }
  }, [data]);

  const fileinputChange = async (event) => {
    try {
      const res = await Taro.chooseImage({
        count: 9, // 最多选择数量
        sizeType: ['original', 'compressed'], // 图片格式
        sourceType: ['album', 'camera'], // 来源
      });
      const imageList = (await upload(res.tempFilePaths)) || [];
      setList([...list, ...imageList]);
      onChange && onChange([...list, ...imageList]);
    } catch (error) {
      console.error('选择图片失败:', error);
      return [];
    }
  };


  const removeImage = (countNum) => {
    let newList = list.filter((item, index) => {
      return index !== countNum;
    });
    setList(newList);
    onChange && onChange(newList);
  };

  const renderUpload = () => {
    return (
      <View onClick={() => { fileinputChange() }} className={className ? className : 'upload_img_box'}>
        <View>
          <View className="add-bar_icon"></View>
          {toast && <View className="add-bar-toast">{toast}</View>}
        </View>

      </View>
    );
  };

  const renderImg = (item, index) => {
    return (
      <View key={index} className={classChangeName ? classChangeName : 'upload_img_cell'}>
        <View
          className="remove-bar"
          onClick={(e) => {
            e.stopPropagation();
            removeImage(index);
          }}
        ></View>
        <Image mode={'aspectFit'} style={{ width: '100%', height: '100%' }} src={item} />
      </View>
    );
  };

  return (
    <View className="upload_box">
      {list.map((item, index) => {
        return renderImg(item, index);
      })}
      {count > list.length && renderUpload()}
    </View>
  );
};
